package com.formula.datastructure.exercise.tree;

import com.formula.datastructure.util.DataUtil;

public class CompleteTree {
    Integer[] array;

    int lastIdx = -1;

    public CompleteTree(Integer[] input) {
        array = input;
        lastIdx = input.length - 1;
    }

    public CompleteTree(int size) {
        array = new Integer[size];
    }

    public void add(Integer[] data) {
        for (Integer item : data) {
            add(item);
        }
    }

    public void add(Integer data) {
        if (array.length > lastIdx + 1) {
            array[++lastIdx] = data;
        }
    }

    // 千万记得parent需要先-1
    public Integer getParent(int idx) {
        return idx == 0 ? -1 : array[(idx - 1) / 2];
    }

    public Integer getLeft(int idx) {
        return array[idx * 2 + 1];
    }

    public Integer getRight(int idx) {
        return array[idx * 2 + 2];
    }

    public static void main(String[] args) {
        CompleteTree tree = new CompleteTree(50);
        Integer[] data = DataUtil.genUniqueArray(20, 100);
        DataUtil.printIndex(20);
        DataUtil.printArray(data);
        tree.add(data);
        System.out.println(tree.getParent(12));
    }
}
